package rensoft.android.json;

import org.json.JSONException;

import java.util.Iterator;

import static rensoft.java.lang.Lang.error;
import static rensoft.java.lang.Lang.is;

import rensoft.java.json.JSONContainer;
import rensoft.java.json.JSONObject;
import rensoft.java.json.JSONType;
import rensoft.java.json.JsonObjectImplBase;



public class JSONObjectImpl extends JsonObjectImplBase {

  private final org.json.JSONObject value;

  public JSONObjectImpl() {
    this(new org.json.JSONObject());
  }

  public JSONObjectImpl(org.json.JSONObject value) {
    super(value);
    this.value = value;
  }

  @Override
  public JSONContainer asContainer() {
    return this;
  }

  @Override
  public JSONObject asObject() {
    return this;
  }

  @Override
  public JSONType getImpl(String key) {
    Object valuekey = null;
    try {
      valuekey = value.get(key);
    } catch (Exception e) {}
    if (is(valuekey)) return JSONImpl.create(valuekey);
    return null;
  }

  public int getSize() {
    return value.length();
  }

  @SuppressWarnings("unchecked")
  public Iterator<String> iterator() {
    return value.keys();
  }

  public void put(String key, JSONType value) {
    try {
      this.value.put(key, value.getValue());
    } catch (JSONException e) {
      error(e);
    }
  }

  public String toJSON() {
    return value.toString();
  }
}
